package com.lin.zoo.view;

import com.lin.zoo.util.DataBase;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class ActivityParkPage {
    private JFrame frame=new JFrame("查看园区活动");//新窗口
    private JTable jTable;//使用表格展示数据
    private DefaultTableModel mol;
    private JScrollPane scrollPane;//添加滚轮
    private Vector<String> rowVector;//存放列数据
    private Vector<Vector<String>> dataVector;//存放数据
    private Connection con;
    private PreparedStatement state;
    private ResultSet rs;

    public void createAndShowGUI(Object id)throws SQLException{
        frame.setVisible(true);
        frame.setSize(1000,400);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 显示窗口
        frame.setResizable(false);
        //固定窗口大小不被修改
        frame.setLocationRelativeTo(null);
        //窗口处于中央
        rowVector= new Vector<>();
        rowVector.add("id");
        rowVector.add("活动介绍");
        rowVector.add("所在园区");
        rowVector.add("开始时间");
        rowVector.add("结束时间");//列名称
        mol = new DefaultTableModel();
        try{
            con = DataBase.getCon();
            state = con.prepareStatement("select * from activity where parkid=?");//读取所选园区的活动信息
            state.setObject(1,id);
            rs=state.executeQuery();
        }catch (ClassNotFoundException e) {
            System.out.println("数据读取错误"+this.getClass().getName());
        }//直接在view中调用了数据库
        setData(rs);//将读取的数据存放在dataVector中
        DataBase.close(state, con);
        jTable=new JTable(mol);
        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane=new JScrollPane(jTable);

        TableColumn introductionColumn = jTable.getColumnModel().getColumn(1);
        introductionColumn.setPreferredWidth(800);//修改介绍一列的行距

        TableColumn idColumn = jTable.getColumnModel().getColumn(0);
        idColumn.setPreferredWidth(20);//修改id一行的行距

        jTable.setRowHeight(50);
        frame.add(scrollPane, BorderLayout.CENTER);//添加滚轮

    }
    //将读取到的数据放置到dataVector
    public void setData(ResultSet rs) throws SQLException {
        dataVector = new Vector<>();
        while(rs.next()) {
            Vector<String> vector = new Vector<>();
            for (int i = 1; i <= 5; i++)//5代表列数
                vector.add(rs.getString(i));//添加数据库数据到vector
            dataVector.add(vector);//添加vector数据到dataVector
        }
        mol.setDataVector(dataVector,rowVector);//最后将数据输入至mol
    }
}
